import axios, {AxiosResponse, InternalAxiosRequestConfig} from 'axios'
import pinia from '../store/pinia'
import {ElLoading} from 'element-plus'
import { userStore } from '../store/user'
const store = userStore(pinia)


const baseUrl1:string = "http://megasensing.cn:4000/" // 外网数据
const baseUrl2:string = import.meta.env.VITE_APP_BASEURL_MAIN // 本地串口数据
const baseUrl3:string = import.meta.env.VITE_APP_BASEURL_ADMIN // 后台接口

// 本地串口接口
const instace = axios.create({
    baseURL: baseUrl2,
    timeout: 8000
})
// 配置请求拦截器
instace.interceptors.request.use((config:InternalAxiosRequestConfig) => {
    // loadingInstance = ElLoading.service({
    //     background: 'rgba(0,0,0,.3)'
    // })
    return config
})

// 配置响应拦截器
instace.interceptors.response.use((config:AxiosResponse) => {
    // loadingInstance.close()
    return config
})

// 本地串口接口
const adminInstance = axios.create({
    baseURL: baseUrl3,
    timeout: 8000
})
let loadingInstance:any = null
// 配置请求拦截器
adminInstance.interceptors.request.use((config:InternalAxiosRequestConfig) => {
    loadingInstance = ElLoading.service({
        background: "rgba(255,255,255,.1)",
        text: "加载中请稍等"
    })
    return config
})

// 配置响应拦截器
adminInstance.interceptors.response.use((config:AxiosResponse) => {
    loadingInstance.close()
    return config
},(err:any) => {
    loadingInstance.close()
})

// 下载excel数据的响应
const downInstance = axios.create({
    baseURL: baseUrl3,
    timeout: 100000000000000000
})

let loadingInstance1:any = null

downInstance.interceptors.request.use((config) => { 
    store.initNum = 0
    let timers = Math.floor(store.total / 35890)
    let speed = Math.floor(100 / timers)
    loadingInstance1 = setInterval(() => {
        console.log(timers)
        if (timers > 0) {
            timers --
            store.initNum += speed
        } else {
            console.log("要结束了")
            clearInterval(loadingInstance1)
        }
    },1000)
    console.log(timers)
    return config
})

downInstance.interceptors.response.use((config) => {
    store.initNum = 100
    clearInterval(loadingInstance1)
    return config
})
// let loadingInstance:any = null



// 外网的接口
const networkInstace = axios.create({
    baseURL: baseUrl1,
    timeout: 8000
})

// let loadingInstance:any = null
// 配置请求拦截器
networkInstace.interceptors.request.use((config:InternalAxiosRequestConfig) => {
    // loadingInstance = ElLoading.service({
    //     background: 'rgba(0,0,0,.3)'
    // })
    return config
})

// 配置响应拦截器
networkInstace.interceptors.response.use((config:AxiosResponse) => {
    // loadingInstance.close()
    return config
})


export default {instace,networkInstace,downInstance,adminInstance}